package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.AdminLoginConstant;
import com.dongdongshop.constant.SellerLoginConstant;
import com.dongdongshop.pojo.TbAdminUser;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.result.Result;
import com.dongdongshop.result.ResultEnum;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Controller
public class SellerLoginController {

    private static final Logger logger = LoggerFactory.getLogger(SellerLoginController.class);

    @Reference
    private SellerService sellerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping({"/","toLogin"})
    public String toLogin(){
        return "shoplogin";
    }

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("sellerRegister")
    @ResponseBody
    public Result sellerRegister(TbSeller tbSeller){
        try {
            String salt = ShiroUtils.generateSalt(6);
            tbSeller.setSalt(salt);
            String password = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt,3);
            tbSeller.setPassword(password);
            int i =sellerService.insertSeller(tbSeller);
            return Result.jsonResponse(ResultEnum.OK);
        }catch (Exception e){
            logger.error("系统报错",e);
            return Result.jsonResponse(ResultEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("sellerLogin")
    public String sellerLogin(String sellerId,String password, Model model){
        if (null == sellerId || "".equals(sellerId) ||
             null == password || "".equals(password)){
            model.addAttribute("message","用户名或者密码不能为空");
            return "shoplogin";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token =new UsernamePasswordToken(sellerId,password);

        String sellerLoginErrorCount =  SellerLoginConstant.SELLER_LOGIN_ERROR_COUNT + sellerId;
        String sellerLoginErrorLock = SellerLoginConstant.SELLER_LOGIN_ERROR_LOCK + sellerId;

        if (redisTemplate.hasKey(sellerLoginErrorLock)){
            model.addAttribute("message","由     于密码错误次数已达上限，请在"+redisTemplate.getExpire(sellerLoginErrorLock, TimeUnit.MINUTES)+"分钟后再试");
            return "/shoplogin";
        }

        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            model.addAttribute("message","用户未注册");
            return "/shoplogin";
        }catch (IncorrectCredentialsException e){
            if (!redisTemplate.hasKey(sellerLoginErrorCount)){
                redisTemplate.opsForValue().set(sellerLoginErrorCount,1);
                redisTemplate.expire(sellerLoginErrorCount,2, TimeUnit.MINUTES);
                model.addAttribute("message","在120内还可以输入四次密码");
                return "/shoplogin";
            }else {
                Long count  = Long.parseLong( redisTemplate.opsForValue().get(sellerLoginErrorCount).toString());
                if (count < 4){
                    Long increment = redisTemplate.opsForValue().increment(sellerLoginErrorCount, 1);
                    Long expire = redisTemplate.getExpire(sellerLoginErrorCount, TimeUnit.SECONDS);
                    model.addAttribute("message","在"+expire+"秒内，还可以输入"+(5 - increment)+"次密码");
                    return "/shoplogin";
                }else {
                    redisTemplate.opsForValue().set(sellerLoginErrorLock,"lock");
                    redisTemplate.expire(sellerLoginErrorLock,1,TimeUnit.HOURS);
                    model.addAttribute("message","该账号已被冻结，请站在一小时后再试");
                    return "/shoplogin";
                }
            }
        }

        redisTemplate.delete(sellerLoginErrorCount);
//        model.addAttribute("message","登录成功");
//        TbSeller seller =  (TbSeller) SecurityUtils.getSubject().getPrincipal();
//        model.addAttribute("seller", seller.getSellerId());
        return "redirect:/index/toIndexShow";
    }
}
